package com.zhongyewx.teachercert.utils;
import android.content.Context;
import android.os.Looper;
import android.support.annotation.StringRes;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zhongyewx.teachercert.R;

import java.lang.ref.WeakReference;

public class ZYToastUtil {

    private static Toast toast = null;
    private static WeakReference<Toast> toastWeakReference;

    public static void showToast(Context context, String content) {
        if (toast != null) {
            toast.cancel();
        }
        if (Looper.getMainLooper() != Looper.myLooper()){
            return;
        }
        toastWeakReference = new WeakReference<>(Toast.makeText(context, content, Toast.LENGTH_SHORT));
        toastWeakReference.get().setDuration(Toast.LENGTH_SHORT);
        toastWeakReference.get().show();
    }
    public static void showToast(Context context, @StringRes int resId) {
        if (toast != null) {
            toast.cancel();
        }
        if (Looper.getMainLooper() != Looper.myLooper()){
            return;
        }
        toastWeakReference = new WeakReference<>(Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT));
        toastWeakReference.get().setDuration(Toast.LENGTH_SHORT);
        toastWeakReference.get().show();
    }
    public static void showCenterToast(Context context, @StringRes int resId) {
        if (toast != null) {
            toast.cancel();
        }
        if (Looper.getMainLooper() != Looper.myLooper()){
            return;
        }
        toastWeakReference = new WeakReference<>(new Toast(context));
        toastWeakReference.get().setDuration(Toast.LENGTH_SHORT);
//        toast = Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT);
        View view = View.inflate(context, R.layout.toast_layout, null);
        TextView tv_toast = (TextView) view.findViewById(R.id.tv_toast);
        tv_toast.setText(context.getResources().getString(resId));
        toastWeakReference.get().setView(view);
        toastWeakReference.get().setGravity(Gravity.CENTER, 0, 0);
        toastWeakReference.get().show();
    }
    public static void showCenterToast(Context context, String s) {
        if (toast != null) {
            toast.cancel();
        }
        if (Looper.getMainLooper() != Looper.myLooper()){
            return;
        }
        toastWeakReference = new WeakReference<>(new Toast(context));
        toastWeakReference.get().setDuration(Toast.LENGTH_SHORT);
        View view = View.inflate(context, R.layout.toast_layout, null);
        TextView tv_toast = (TextView) view.findViewById(R.id.tv_toast);
        tv_toast.setText(s);
        toastWeakReference.get().setView(view);
        toastWeakReference.get().setGravity(Gravity.CENTER, 0, 0);
        toastWeakReference.get().show();
    }
}
